package com.lizi.MarkHsiu;
import java.lang.reflect.Field;

import  sun.misc.Unsafe ;
@SuppressWarnings("restriction")
public class ObjectLocation {
	
	public static void main(String[] args) throws Exception {
		Field f = Unsafe.class.getDeclaredField("theUnsafe"); // Internal reference
		f.setAccessible(true);
		Unsafe unsafe1 = (Unsafe) f.get(null);
		// This creates an instance of player class without any initialization
		Player p = (Player) unsafe1.allocateInstance(Player.class);
		System.out.println(p.getAge()); // Print 0
		p.setAge(45); // Let's now set age 45 to un-initialized object
		System.out.println(p.getAge()); // Print 45
		
		Unsafe unsafe = getUnsafeInstance();
		Field appleField = ObjectLocation.class.getDeclaredField("apple");
		System.out.println("Location of Apple: " + unsafe.staticFieldOffset(appleField));
		Field orangeField = ObjectLocation.class.getDeclaredField("orange");
		System.out.println("Location of Orange: " + unsafe.objectFieldOffset(orangeField));
	}

	private static Unsafe getUnsafeInstance()
			throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
		Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
		theUnsafeInstance.setAccessible(true);
		return (Unsafe) theUnsafeInstance.get(Unsafe.class);
	}
}
